from secrets import randbelow
from bisect import bisect_right


def weight_random(m: dict) -> str:
    # m {"good_uuid": weight}
    all_weight = 0

    bisect_section = []
    ks = []

    for k, v in m.items():
        all_weight += v
        bisect_section.append(all_weight)
        ks.append(k)

    x = randbelow(all_weight)
    idx = bisect_right(bisect_section, x)

    return ks[idx]


def quanjushang_raffle(user_weight: dict, boss_goods_count: dict):
    # user_weight: {"user_uuid": ticket_count}
    # goods: {"good_uuid": good_count}

    def _wxs_raffle_one_boss_prize(user_weight: dict, good_uuid, good_count):
        # user_uuid_list
        ks = []
        # user weight section used for bisect
        bisect_section = []
        all_weight = 0

        for user_uuid, ticket_count in user_weight.items():
            ks.append(user_uuid)
            all_weight += ticket_count

            bisect_section.append(all_weight)

        res = {}
        for _ in range(good_count):
            x = randbelow(all_weight)
            idx = bisect_right(bisect_section, x)
            if ks[idx] not in res:
                res[ks[idx]] = 1
            else:
                res[ks[idx]] += 1

        return res

    res = {}
    for good_uuid, good_count in boss_goods_count.items():
        one_prize_res = _wxs_raffle_one_boss_prize(user_weight, good_uuid, good_count)
        res[good_uuid] = one_prize_res
    return res
